package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.DirectMchntBaseInfo;
import cc.rengu.redp.bizimpl.upmp.domain.DirectMchntSignInfo;
import cc.rengu.redp.bizimpl.upmp.dao.DirectMchntSignInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 刘玉亮.LL
 */
@Service
public class DirectMchntSignInfoServiceImpl extends ServiceImpl<DirectMchntSignInfoMapper, DirectMchntSignInfo> implements IDirectMchntSignInfoService {

    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpPrivilegeCheckService upmpPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;

    @Autowired
    private IDirectMchntBaseInfoService directBaseInfoService;
    @Override
    public DirectMchntSignInfo getByMchntCd(String mchntCd) {
        LambdaQueryWrapper<DirectMchntSignInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DirectMchntSignInfo::getMchntCd,mchntCd);
        return this.getOne(wrapper);
    }

    @Override
    @Transactional(value = "transactionManager")
    public OperationResult saveData(String oprMenuId, String oprMenuName, DirectMchntSignInfo entity, HttpServletRequest request, String webNextUrl, String flag) throws RedpException {
//        String flag = request.getParameter("optFlag");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

//        entity.setInstId(user.getInstId());
        //
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            UpmpPrivilegeCheck privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "银联直连商户管理:新增");
            // 重复新增，变为修改操作
            if (StringUtils.isNotBlank(entity.getMchntCd())) {
                DirectMchntSignInfo byMchntCd = this.getByMchntCd(entity.getMchntCd());
                if (null != byMchntCd) {
                    entity.setId(byMchntCd.getId());
                } else {
                    entity.setId(null);
                }
            } else {
                entity.setId(null);
            }

            entity.setOprId(user.getId());
            entity.setCrtOrgId(org.getOrgCode());
            entity.setCreateTime(lastUpddt);
            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            // 非正式  新增-待提交审批
            entity.setMchntSignStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType());
            // 入正式表
            this.save(entity);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                bizTmpService.saveBizTmpDtl(entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                        , oprMenuId, oprMenuName, entity.getMchntSignStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl, "", "", entity.getMchntCd(), null, null);
            } else {
                // 录入历史表，状态改为 正式 新增-审核通过；
                DirectMchntSignInfo directSignInfo = new DirectMchntSignInfo();
                BeanUtils.copyProperties(entity, directSignInfo);
                directSignInfo.setMchntSignStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());

                bizHisService.saveBizHisNew(directSignInfo, directSignInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                        , oprMenuId, oprMenuName, entity.getId(), entity.getMchntCd(), null, null);
            }
            result.put("id", entity.getId());
            result.put("mchntCd", entity.getMchntCd());
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
            // 上一次操作如果是新增-待提交审批的，前端传来upd标志，转到add方法处理
            DirectMchntBaseInfo directBaseInfo = directBaseInfoService.getByMchntCd(entity.getMchntCd());
            if (directBaseInfo.getAuditStatus().equals(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_NOTCOMMIT.getType())) {
                //
                return this.saveData(oprMenuId, oprMenuName, entity, request, webNextUrl, "add");
            }
            //
            String auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_UPD_NOTCOMMIT.getType();
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }

            UpmpPrivilegeCheck privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "银联直连商户管理:修改");
            DirectMchntSignInfo dbDirectSignInfo = this.getById(id);
            DirectMchntSignInfo directSignInfo = new DirectMchntSignInfo();
            BeanUtils.copyProperties(entity, directSignInfo);

            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            entity.setMchntSignStatus(dbDirectSignInfo.getMchntSignStatus());

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                dbDirectSignInfo.setLastOprId(user.getId());
                dbDirectSignInfo.setLastUpdateTime(lastUpddt);
                // 修改-待提交审批
                dbDirectSignInfo.setAuditStatus(auditStatus);

                this.updateById(dbDirectSignInfo);

                //检查临时表是否有数据，如果没用则新增
                entity.setAuditStatus(auditStatus);
                directSignInfo = new DirectMchntSignInfo();
                BeanUtils.copyProperties(dbDirectSignInfo, directSignInfo);
                BeanUtils.copyProperties(entity, directSignInfo);

                bizTmpService.saveBizTmpDtl(directSignInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , oprMenuId, oprMenuName, directSignInfo.getMchntSignStatus(), directSignInfo.getAuditStatus(), directSignInfo.getId(), webNextUrl, "", "", directSignInfo.getMchntCd(), null, null);
                result.put("id", directSignInfo.getId());
            } else {
                // 修改-待提交审批
                entity.setAuditStatus(auditStatus);

                BeanUtils.copyProperties(entity, directSignInfo);
                this.updateById(directSignInfo);

                // 录入历史表，状态改为 正式 修改-审核通过；
                directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                //历史表新增
                bizHisService.saveBizHisNew(directSignInfo, dbDirectSignInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , oprMenuId, oprMenuName, directSignInfo.getId(), directSignInfo.getMchntCd(), null, null);
            }
            result.put("id", entity.getId());
            result.put("mchntCd", entity.getMchntCd());
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }
            DirectMchntSignInfo dbDirectSignInfo = this.getById(id);
            if (Common.isBlank(dbDirectSignInfo)) {
                log.error("根据id没有找到指定数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
            }

            DirectMchntSignInfo directSignInfo = new DirectMchntSignInfo();
            BeanUtils.copyProperties(dbDirectSignInfo, directSignInfo);

            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "银联直连商户管理:停用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    // 停用-待提交审批
                    directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_NOTCOMMIT.getType());
                } else {
                    // 停用-审核通过
                    directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "银联直连商户管理:启用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    // 启用-待提交审批
                    directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_NOTCOMMIT.getType());
                } else {
                    // 启用-审核通过
                    directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "银联直连商户管理:注销");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    // 注销-待提交审批
                    directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_NOTCOMMIT.getType());
                } else {
                    // 注销-审核通过
                    directSignInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                }
            }
            directSignInfo.setLastOprId(user.getId());
            directSignInfo.setLastUpdateTime(lastUpddt);
            this.updateById(directSignInfo);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmpDtl(directSignInfo, user, org.getInstId(), bizOpr, lastUpddt
                        , oprMenuId, oprMenuName, directSignInfo.getMchntSignStatus(), directSignInfo.getAuditStatus(), directSignInfo.getId(), webNextUrl, "", "", directSignInfo.getMchntCd(), null, null);
            } else {
                //历史表新增
                bizHisService.saveBizHisNew(entity, directSignInfo, user, org.getInstId(), bizOpr, lastUpddt
                        , oprMenuId, oprMenuName, directSignInfo.getId(), directSignInfo.getMchntCd(), null, null);
            }
            result.put("id", directSignInfo.getId());
            result.put("mchntCd", directSignInfo.getMchntCd());
        }

        result.put("formNm", "signInfo");

        if(!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)&&!PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)){
            return OperationResult.buildSuccessResult("", result);
        }else{
            return OperationResult.buildSuccessResult("数据保存处理完成", result);
        }
    }
}
